﻿using System;
using System.IO;
using System.Windows.Forms;
using Xin478.CSWork.Common;
using Xin478.MySocket;


namespace Xin478.CSWork.Client
{
    public partial class LoginForm : MyForm
    {
        public string 状态 { get { return this.状态标签.Text; } set { this.状态标签.Text = value;  } }
        public bool 登陆成功 {  set { this.DialogResult = DialogResult.OK;  }  }
        public string 用户名 { get { return this.用户名下拉框.Text; } set { this.用户名下拉框.Text = value; } }
        public string 密码 { get { return this.密码框.Text; } set { this.密码框.Text = value; } }
        public bool 自动登录 { get { return this.自动登录复选框.Checked; } }
        public bool 锁定登录 { get { return !this.登陆按钮.Enabled; } set { this.用户名下拉框.Enabled = !value; this.密码框.Enabled = !value; this.登陆按钮.Enabled = !value; } }

        public event EventHandler 提交事件;

        public LoginForm()
        {
            InitializeComponent();
            this.Load += new EventHandler(LoginForm_Load);
            this.用户名下拉框.KeyDown += new KeyEventHandler(LoginForm_KeyDown);
            this.密码框.KeyDown += new KeyEventHandler(LoginForm_KeyDown);
            this.自动登录复选框.KeyDown += new KeyEventHandler(LoginForm_KeyDown);
        }

        void LoginForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) this.登陆按钮.Focus();
        }

        void LoginForm_Load(object sender, EventArgs e)
        {
            if (Directory.Exists(Application.StartupPath + "\\Users\\"))
            {
                foreach (string user in Directory.GetDirectories(Application.StartupPath + "\\Users\\"))
                    this.用户名下拉框.Items.Add(user.Substring(user.LastIndexOf('\\')+1));
            }
        }

        private void 登陆按钮_Click(object sender, EventArgs e)
        {
            bool 是否记住 = this.自动登录复选框.Checked;
            if (string.IsNullOrEmpty(用户名下拉框.Text) || string.IsNullOrEmpty(密码框.Text))
            {
                this.状态标签.Text = "用户名和密码不能为空";
                return;
            }


            if (this.提交事件 != null) this.提交事件(this,e);
        }

        public void 登陆失败()
        {
            MessageBox.Show("错误的用户名或密码");
            this.锁定登录 = false;
        }

        public void LoginForm_OnConnected(object obj, NetEventArgs e)
        {
            WinForm.DoThreadSafe(this, delegate() { this.状态 = "联机"; });
        }
        public void LoginForm_OnUnConnected(object obj, NetEventArgs e)
        {
            WinForm.DoThreadSafe(this, delegate()
            {
                this.状态 = "脱机";
                if (this.锁定登录) this.锁定登录 = false;
            });
        }

    }
}
